package utilities.print.menu.execute.userPortal;

import employee.User;
import utilities.JDBC.Database;
import utilities.JDBC.sql.DeleteUser;
import utilities.JDBC.sql.SelectUserName;
import utilities.print.log.LogMessage;
import utilities.print.menu.MenuExecute;
import utilities.print.menu.execute.Verify;

import java.sql.ResultSet;
import java.util.Scanner;

import static utilities.print.menu.Menu.line;

public class Revise implements MenuExecute {
    private final Database<User> database = new Database<>();
    private final LogMessage Log = new LogMessage("userPortal.revise");
    /**
     * 启动菜单功能类方法
     * @throws Exception 可能产生的异常
     */
    @Override
    public void execute() throws Exception {
        Scanner in = new Scanner(System.in);

        System.out.println("修改账号信息");
        line();
        PrintList.printDatabaseUserInfo();
        System.out.print("输入要更改的账号名字: ");
        String name = in.next();
        line();

        ResultSet set = database.executeSelect(new SelectUserName(name));
        if (set.next()){
            //数据库中的账号信息
            User user = database.toObject(
                    set,
                    new User()
                    );
            User user1 = database.toObject(
                    set,
                    new User()
                    );
            //注册的账号名字

            line();
            System.out.print("输入修改账号名: ");
            user.setName(in.next());
            while (database.executeSelect(new SelectUserName(user.getName())).next()){
                System.out.println("账号名重复了,换一个吧");
                System.out.print("输入账号名: ");
                user.setName(in.next());
            }

            //账号密码
            line();
            System.out.print("输入账号密码: ");
            user.setPassword(in.next());
            while (user.getPassword().isEmpty()){
                System.out.println("账号密码不能为空!");
                System.out.print("输入账号密码: ");
                user.setPassword(in.next());
            }

            //删除后添加修改后的信息
            database.executeUpdate(new DeleteUser(name));
            database.executeUpdate(connection ->
                 connection.prepareStatement("insert into userinfo value(" +
                            user.getId() + ",'" +
                            user.getName() + "','" +
                            user.getPassword() +
                            "')"
                    )
            );

            System.out.println("修改账号信息成功!");
            System.out.printf("修改的账号信息 名字:%s,密码:%s\n", user.getName(), user.getPassword());
            database.close();

            Log.print("在数据库修改账号信息: " + user1 + " -> " + user);
            Log.closeOutputFile();

            PrintList.printDatabaseUserInfo();
        }else {
            System.out.printf("找不到名字是 %s 的账号!\n",name);
        }

        line();
        Verify.pressKey("输入任意内容退出");
    }
}
